<html>
<head>
<style>
body {
  min-width:600px;
  overflow-x:hidden;
  background: white;
}

.score {
    float: left;
    color : red;
    font-size: 1.5em;
    background: white;
    min-width: 1.5em;
    text-align: center;
    margin-right: 10px;
}


.meta {
    font-size: 80%;
    color: gray;
}

.created {
    font-style: italic;
}

.post {
    /*border: solid gray 1px;*/
    padding: 3px;
    margin: 10px;
    background: white;
}

.subreddit {
    font-weight: bold;
}

</style>

<script>

var newTab=function(url) {console.error("Unexpected error!")};

window.onload = function ()
{
chrome.tabs.getSelected(null, function (currentTab)
{
    newTab = function (url)
    {
        chrome.tabs.create({url:url, index:currentTab.index+1});
    }
    
    bg = chrome.extension.getBackgroundPage();
    data = bg.getUrlData( currentTab.id );

    if (data.length == 0)
    {
        thisUrl = bg.getUrl(currentTab.id);
        chrome.tabs.create({url: 'http://www.reddit.com/submit?url='+thisUrl});
    }

    posts = []

    data.forEach( function(row)
    {
        if (row.kind != 't3')
        {
            console.error("unexpected row kind: " + row.kind);
            return;
        }
        posts.push( row.data );
    }
    );

    posts.sort( function (a, b) { return b.score - a.score } );

    html = '';
    posts.forEach( function(post)
    {
        html += '<div class="post">\n' ;
        html += ( '  <div class="score">' + post.score + '</div>\n' );
        html += ( '  <div class="title">' + post.title + '</div>\n' );
        html += ( '  <div class="meta">\n' );
        html += ( '    <a href="http://www.reddit.com'+post.permalink+'" onclick="newTab(this.href)">'
                  + post.num_comments + ' comments</a>\n');
        html += ( '    submitted to <span class="subreddit">' + post.subreddit + '</span>\n' );
        html += ( '    by <span>' + post.author + '</span>\n' );
        created = new Date(post.created * 1000);
        html += ( '    at <span class="created">' + created.toDateString() + '</span>\n' );
        html += ( "  </div>\n" );    
        html += ( "</div>\n" );
    }
    );

    document.getElementById('content').innerHTML = html;

}
);

}

</script>
</head>
<body>

<div id="content">
    Still loading! Please click again in a few seconds.
</div>

</body>
</html>
